/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UpdateAtofClient.java
 *
 * Created on Nov 16, 2009, 6:26:52 PM
 */
package org.testis.gui.mvc;

import org.testis.communication.client.AtofFtpClient;
import org.testis.gui.utils.AtofGuiManifestInfo;
import org.testis.utils.TerminalApplicationExecutor;
import org.testis.utils.UserSettingsManager;
import java.io.IOException;
import java.util.Arrays;
import javax.swing.JOptionPane;

/**
 *
 * @author nurhat
 */
public class UpdateGui extends javax.swing.JDialog {

    private static String ATOF_GUI_HOME = System.getenv("ATOF_GUI_HOME");

    /** Creates new form UpdateAtofClient */
    public UpdateGui(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        btnUpdate = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtUpdateLog = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Atof Gui Updater");

        jPanel2.setName("jPanel2"); // NOI18N

        btnUpdate.setText("Update");
        btnUpdate.setName("btnUpdate"); // NOI18N
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnClose.setText("Close");
        btnClose.setName("btnClose"); // NOI18N
        btnClose.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCloseMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnUpdate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnClose)
                .addContainerGap(365, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnUpdate)
                    .addComponent(btnClose)))
        );

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        txtUpdateLog.setColumns(20);
        txtUpdateLog.setRows(5);
        txtUpdateLog.setName("txtUpdateLog"); // NOI18N
        jScrollPane1.setViewportView(txtUpdateLog);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCloseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCloseMouseClicked
        dispose();
    }//GEN-LAST:event_btnCloseMouseClicked

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        updateGui();
    }//GEN-LAST:event_btnUpdateActionPerformed

    public void updateGui() {
        AtofGuiManifestInfo info = new AtofGuiManifestInfo();
        String currentVersion = "v." + info.getSpecificationVersion();
        String currentRevision = "r." + info.getImplementationVersion();
        txtUpdateLog.append("\nCurrent version is:" + currentVersion + " Current Revision is:" + currentRevision + "..");

        String updatesPath = ATOF_GUI_HOME + "/updates/";
        String ftpPath = "/ATOFSETUPS/";
        String maxRevisionFolder = "", maxVersionFolder = "", maxVersion = "", maxRevision = "";

        String url = UserSettingsManager.getInstance().getUpdateUrl();
        String userName = UserSettingsManager.getInstance().getUpdateUserName();
        String password = UserSettingsManager.getInstance().getUpdatePassword();
        AtofFtpClient ftpManager = new AtofFtpClient(url,
                userName,
                password);

        if (!ftpManager.connectTo()) {
            txtUpdateLog.append("\nCan not connect to " + UserSettingsManager.getInstance().getUpdateUrl() + " ...");
            return;
        }
        if (!ftpManager.loginTo()) {
            txtUpdateLog.append("\nCan not login to " + UserSettingsManager.getInstance().getUpdateUrl() + " ...");
            return;
        }
        try {

            String[] versionNames = ftpManager.listNames(ftpPath);
            if (versionNames.length > 0) {
                Arrays.sort(versionNames);
                maxVersionFolder = versionNames[versionNames.length - 1];
                maxVersion = versionNames[versionNames.length - 1].replace(ftpPath, "");
                txtUpdateLog.append("\nFound following versions:");
                for (String name : versionNames) {
                    txtUpdateLog.append("\n\t" + name);
                }
                txtUpdateLog.append("\nMax version is " + maxVersion + "Retrieving revision information..");
                String[] revisionNames = ftpManager.listNames(maxVersionFolder);
                txtUpdateLog.append("\nFound following revisions:");
                if (revisionNames.length > 0) {

                    Arrays.sort(revisionNames);
                    for (String name : revisionNames) {
                        txtUpdateLog.append("\n\t" + name);
                    }
                    maxRevisionFolder = revisionNames[revisionNames.length - 1];
                    maxRevision = revisionNames[revisionNames.length - 1].replace(maxVersionFolder + "/", "");
                    txtUpdateLog.append("\nMax revision is " + maxRevision + "...");
                } else {
                    txtUpdateLog.append("\n No  revision found for version " + maxVersion + "...");
                }
            } else {
                txtUpdateLog.append("\n No  version found...");
            }
        } catch (IOException e) {
            System.out.println("An error occured.." + e.getMessage());
        } finally {
            ftpManager.logoutFrom();
        }
        if (maxVersion.isEmpty() || maxRevision.isEmpty()) {
            System.out.println("Can not get new version info from ftp..");
            return;
        }
        int resultVersion = maxVersion.compareToIgnoreCase(currentVersion);
        int resultRevision = maxRevision.compareToIgnoreCase(currentRevision);
        if (resultVersion == 0 || resultVersion > 0) {
            if (resultRevision > 0) {
                String app = "wget -r -q  ftp://" + userName + ":" + password + "@" + url + maxRevisionFolder + "/atofgui -P " + updatesPath;
                txtUpdateLog.append("\nDownloading new version..." + app);
                System.out.println(app);
                TerminalApplicationExecutor executor = new TerminalApplicationExecutor(app);
                int exitCode = 1;
                try {
                    exitCode = executor.runExec();
                } catch (InterruptedException ex) {
                    txtUpdateLog.append("\nError occured while downloading new version." + ex.getMessage());
                } catch (IOException ex) {
                    txtUpdateLog.append("\nError occured while downloading new version." + ex.getMessage());
                }
                if (exitCode == 0) {
                    txtUpdateLog.append("\nNew version downloaded to " + updatesPath + "...");
                    txtUpdateLog.append("\nUpdating your application...");
                    String updatesFullPath = updatesPath + "\\" + url + "\\" + ftpPath + "\\" + maxVersion + "\\" + maxRevision + "\\";
                    String atofguiSetupExe = updatesFullPath + "\\atofgui\\" + "AtofGuiSetup-" + maxVersion + " " + maxRevision + ".exe";
                    System.out.println(atofguiSetupExe);
                    UserSettingsManager.getInstance().setUpdateRequired(Boolean.TRUE);
                    int result =
                            JOptionPane.showConfirmDialog(null,
                            "Do you want to start update? Your application will be closed...",
                            "Atof Gui Update",
                            javax.swing.JOptionPane.YES_NO_OPTION,
                            javax.swing.JOptionPane.QUESTION_MESSAGE);
                    if (result == JOptionPane.YES_OPTION) {
                        try {
                            Runtime.getRuntime().exec(atofguiSetupExe);
                            System.exit(0);
                        } catch (IOException ex) {
                            txtUpdateLog.append("\nUpdate failed..." + ex.getMessage());
                        }
                    }

                }
            } else {
                txtUpdateLog.append("\nYour application already up to date...");
            }
        } else {
            txtUpdateLog.append("\nYour application already up to date...");
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtUpdateLog;
    // End of variables declaration//GEN-END:variables
}
